package com.aurora.demo.service;

import com.aurora.demo.api.param.QueryParam;
import com.aurora.demo.entity.Keogram;
import com.aurora.demo.repository.KeogramRepository;
import com.aurora.demo.util.KeogramUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class KeogramService {

    @Autowired
    private KeogramRepository keogramRepository;

    public byte[] getKeogram(List<String> nameList) {
        BufferedImage bi = KeogramUtil.getKeogram(KeogramUtil.getKeogramList(nameList));
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(bi, "JPEG", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();
    }

    public void save(MultipartFile file) {
        try {
            String name = file.getOriginalFilename().substring(0, 13);
            int keoB[] = new int[440];
            byte[] sourceBytes = new byte[0];
            sourceBytes = file.getBytes();
            InputStream in = new ByteArrayInputStream(sourceBytes);
            BufferedImage source = ImageIO.read(in);
            for(int i=0;i<440;i++)
            {
                keoB[i] = source.getRGB(221, i);
            }
            Keogram keogram = new Keogram();
            keogram.setName(name);
            keogram.setKeogram(keoB);
            keogramRepository.save(keogram);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
